package com.srtp.secureprotocol.controller

import com.srtp.secureprotocol.main.SecureProtocol
import com.srtp.secureprotocol.serializable.req.Bundle
import com.srtp.secureprotocol.serializable.resp.IdentityKey
import com.srtp.secureprotocol.serializable.resp.InitializeResponse
import com.srtp.secureprotocol.serializable.resp.PreKey
import com.srtp.secureprotocol.serializable.resp.SignedPreKey
import com.srtp.secureprotocol.util.JsonConverter
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.ApplicationCall
import io.ktor.server.response.respond

class InitializeController {
    fun handleInitialize(
        userId: String,
        password: String,
        secureProtocol: SecureProtocol
    ): InitializeResponse {
        return try {
            val result = secureProtocol.initialize(userId, password, null)
                ?: throw IllegalStateException("Initialization returned null")

            InitializeResponse(
                identityKey = JsonConverter.parseIdentityKey(result.getJSONObject("identityKey")),
                signedPreKey = JsonConverter.parseSignedPreKey(result.getJSONObject("signedPreKey")),
                preKeys = JsonConverter.parsePreKeys(result.getJSONArray("preKeys")),
                passwordHash = result.getString("passwordHash"),
                passwordSalt = result.getString("passwordSalt"),
                oneTimeId = result.getString("oneTimeId"),
                localId = result.getInt("localId")
            )
        } catch (e: Exception) {
            InitializeResponse(
                identityKey = IdentityKey(-1, "", "", "", ""),
                signedPreKey = SignedPreKey(-1, "", "", "", "", ""),
                preKeys = emptyList(),
                passwordHash = "",
                passwordSalt = "",
                oneTimeId = "",
                localId = -1
            ).apply {
                this.identityKey.timestamp = "error: ${e.message ?: "Unknown error"}"
            }
        }
    }

    suspend fun reInitialized(
        bundle: Bundle,
        userId: String,
        password: String,
        secureProtocol: SecureProtocol,
        call: ApplicationCall
    ) {
        try {
            val bundleJson = JsonConverter.convertBundleToJson(bundle)
            secureProtocol.reInitialize(bundleJson, password, userId, null)
            call.respond(HttpStatusCode.OK)
        } catch (e: Exception) {
            call.respond(
                HttpStatusCode.BadRequest,
                "Reinitialization failed: ${e.message ?: "Unknown error"}"
            )
        }
    }

    suspend fun decryptPreKeys(
        preKeys: List<PreKey>,
        secureProtocol: SecureProtocol,
        call: ApplicationCall
    ) {
        try {
            val preKeysJson = JsonConverter.convertPreKeysToJson(preKeys)
            secureProtocol.decryptPreKeys(preKeysJson)
            call.respond(HttpStatusCode.OK)
        } catch (e: Exception) {
            call.respond(
                HttpStatusCode.BadRequest,
                "Decryption failed: ${e.message ?: "Unknown error"}"
            )
        }
    }

    fun createPasswordHashRequest(
        password: String,
        salt: String,
        secureProtocol: SecureProtocol
    ): String {
        return try {
            secureProtocol.createPasswordHash(password, salt)
        } catch (e: Exception) {
            "handle wrong"
        }
    }

    suspend fun createNewPasswordHash(
        request: String,
        secureProtocol: SecureProtocol,
        call: ApplicationCall
    ) {
        try {
            secureProtocol.createNewPasswordHash(request)
            call.respond(HttpStatusCode.OK)
        } catch (e: Exception) {
            call.respond(
                HttpStatusCode.BadRequest,
                "Decryption failed: ${e.message ?: "Unknown error"}"
            )
        }
    }
}